export default function sendRequests(requests, concurrency = 5, retryCount = 3) {
    return new Promise((resolve, reject) => {
        let currentIndex = 0
        let executeIndex = 0
        let stop = false
        const results = []

        const next = (request, resultIndex, errorCount = 1) => {
            if (!request || stop) {
                return
            }

            request()
                .then((response) => {
                    executeIndex++
                    currentIndex++
                    results[resultIndex] = response

                    next(requests[currentIndex], currentIndex)
                })
                .catch((error) => {
                    if (errorCount < retryCount) {
                        next(request, resultIndex, errorCount + 1)
                    } else {
                        results[resultIndex] = error
                        stop = true
                        reject(error)
                    }
                })
                .finally(() => {
                    if (executeIndex >= requests.length) {
                        resolve(results)
                    }
                })
        }

        while (currentIndex < concurrency) {
            next(requests[currentIndex], currentIndex)
            currentIndex++
        }
        currentIndex--
    })
}